package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.service.UserService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断是否有地址
        AddressBook addressBook = addressBookMapper.queryById(ordersSubmitDTO.getAddressBookId());
        if (ObjectUtils.isEmpty(addressBook)) throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        //判断购物车是否有物品
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.queryByUserId(BaseContext.getCurrentId());
        if (ObjectUtils.isEmpty(shoppingCarts)) throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        //创建订单对象，封装数据
        Orders orders = new Orders();
        //将已有值进行拷贝
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()+BaseContext.getCurrentId()));
        //订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //用户id
        orders.setUserId(BaseContext.getCurrentId());
        //创建时间
        orders.setOrderTime(LocalDateTime.now());
        //支付状态
        orders.setPayStatus(Orders.PENDING_PAYMENT);
        //查询用户信息
        User user = userMapper.queryById(BaseContext.getCurrentId());
        //用户姓名
        orders.setUserName(user.getName());
        //收货地址
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        //手机号
        orders.setPhone(addressBook.getPhone());

        //订单插入数据库
        orderMapper.insert(orders);

        //订单详细表
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,detail);
            detail.setOrderId(orders.getId());
            orderDetails.add(detail);
        }
        //插入数据库
        orderDetailMapper.insertBatch(orderDetails);

        //清空购物车
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        //返回数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.queryById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过webSocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", "1");
        map.put("orderId", ordersDB.getId());
        map.put("content", "您有新的订单："+outTradeNo+"，请及时处理");

        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);


    }


    /**
     * 查询历史订单
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public Map<String, Object> historyOrders(Integer page, Integer pageSize, Integer status) {
        //获得用户id
        Long userId = BaseContext.getCurrentId();
        //查询历史订单
        //开启分页
        PageHelper.startPage(page,pageSize);
        //查询
        List<OrderVO> orders = orderMapper.queryByUserIdAndStatus(userId, status);
        //查询订单详情
        orders = orders.stream().map(order -> {
            //根据订单id查询订单详情
            List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(order.getId());
            //设置订单详情
            order.setOrderDetailList(orderDetails);
            return order;
        }).collect(Collectors.toList());
        HashMap<String, Object> result = new HashMap<>();
        result.put("total",orders.size());
        result.put("records",orders);
        return result;
    }


    /**
     * 再来一单
     * @param id
     */
    @Transactional
    @Override
    public void repetition(Long id) {
        //根据订单id查询订单
        Orders orders = orderMapper.queryById(id);
        //判断订单是否存在
        if (ObjectUtils.isEmpty(orders)) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //设置属性
        orders.setId(null);
        orders.setNumber(String.valueOf(System.currentTimeMillis()+BaseContext.getCurrentId()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PENDING_PAYMENT);
        orders.setStatus(Orders.PENDING_PAYMENT);
        //插入数据库
        orderMapper.insert(orders);
        //根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(id);
        //设置订单id
        orderDetails.forEach(orderDetail -> orderDetail.setOrderId(orders.getId()));
        //插入数据库
        orderDetailMapper.insertBatch((ArrayList<OrderDetail>) orderDetails);

    }

    /**
     * 根据订单id查询订单
     * @param id
     * @return
     */
    @Override
    public OrderVO queryById(Long id) {
        //根据订单id查询订单
        Orders orders = orderMapper.queryById(id);
        //判断订单是否存在
        if (ObjectUtils.isEmpty(orders)) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //创建Vo对象
        OrderVO orderVO = new OrderVO();
        //设置属性
        BeanUtils.copyProperties(orders,orderVO);
        //根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(id);
        //设置订单详情
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }


    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        //根据订单id查询订单
        Orders orders = orderMapper.queryById(id);
        //判断订单是否存在
        if (ObjectUtils.isEmpty(orders)) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //判断订单状态
        if (orders.getStatus() != Orders.PENDING_PAYMENT) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //设置属性
        orders.setStatus(Orders.CANCELLED);
        //更新数据库
        orderMapper.update(orders);
    }

    /**
     * 根据条件查询订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public Map<String, Object> queryByCondition(OrdersPageQueryDTO ordersPageQueryDTO) {
        //将当前条件查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //查询
        List<OrderVO> orderVOS = orderMapper.queryByCondition(ordersPageQueryDTO);
        //查询订单详情
        orderVOS = orderVOS.stream().map(orderVO -> {
            //根据订单id查询订单详情
            List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(orderVO.getId());
            //设置订单详情
            orderVO.setOrderDishes(orderDetails.stream().map(OrderDetail::getName).collect(Collectors.joining(",")));
            return orderVO;
        }).collect(Collectors.toList());
        //封装数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("total",orderVOS.size());
        result.put("records",orderVOS);
        return result;
    }

    /**
     * 统计订单
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO vo = new OrderStatisticsVO();
        vo.setConfirmed(orderMapper.queryByStatus(Orders.CONFIRMED));
        vo.setDeliveryInProgress(orderMapper.queryByStatus(Orders.DELIVERY_IN_PROGRESS));
        vo.setToBeConfirmed(orderMapper.queryByStatus(Orders.TO_BE_CONFIRMED));
        return vo;
    }


    /**
     * 接单、派送、拒单、取消、完成
     * @param orders
     */
    @Override
    public void confirm(Orders orders) {
        //修改订单状态
        orderMapper.update(orders);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.queryById(id);
        //判断订单是否存在
        if (ObjectUtils.isEmpty(orders)) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        //通过webSocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", "2");
        map.put("orderId", orders.getId());
        map.put("content", "您的订单："+orders.getNumber()+"，已催单成功");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }
}
